import 'dart:convert';

import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:lib_network/lib_network.dart';

import 'package:lib_util/lib_util.dart';

import '../bridge/bridge_bean.dart';

import '../bridge/native_channel_bridge.dart';

import 'http_api.dart';

import 'http_encrypt.dart';

import 'package:dio/dio.dart';


Future<void> httpInit(List<String>? args, {bool? isDev = false})  async{
  // 本地测试
  HttpConfig().connectTimeout = const Duration(seconds: 30);

  HttpConfig().codeKey = "code";

  HttpConfig().msgKey = "msg";

  HttpConfig().dataKey = "data";

  HttpConfig().successCode = 0;

  const int token_expire = 3002;

  HttpConfig().failCodeList = [
    -1,
    -2,
  ];

  HttpConfig().failCallBack = (code, msg) {
    //这里可以统一处理业务逻辑错误

    if (code == token_expire) {
      NativeChannelBridge().tokenExpire();
    }
  };

  //加解密
  HttpConfig().cryptInterceptor =
      InterceptorsWrapper(onRequest: ((options, handler) {
    //符合条件就加密
    // ['',].contains(options.baseUrl)
    if (options.baseUrl == HttpConfig().baseURL &&
        HttpConfig().isNeedCrypt &&
        options.path.contains('wallet/')&&
        (options.path != API.authGoogle) &&
        (options.path != API.authApple)) {
      var encryptResult =
      Encrypt.encryptString(json.encode(options.queryParameters));

      options.headers["Key"] = encryptResult.iv;

      options.data = encryptResult.base64String;
    } else {
      options.data = json.encode(options.queryParameters);
    }

    options.queryParameters = {};

    options.headers["Content-Type"] = "application/json";

    return handler.next(options);
  }), onResponse: (response, handler) {
    if (response.headers.map.containsKey("Key") &&
        response.headers.value("Key") != null &&
        HttpConfig().isNeedCrypt &&
        (response.requestOptions.path != API.authGoogle) &&
        (response.requestOptions.path != API.authApple)) {
      // print("response.requestOptions => ${response.requestOptions.path}");
      var decryptResult =
          Encrypt.decryptString(response.data, response.headers.value("Key")!);

      response.data = decryptResult;
    }

    return handler.next(response);
  });

  AppCommMsg? commMsg;

  if (args != null && args.length > 0) {
    var json = args[0];

    // print('原生传过来的token：${json}');

    commMsg = NativeChannelBridge().parse(json);
    // 参数 设置 加密信息
  }
  if (commMsg != null) {
    //使用原生传递的参数
    HttpConfig().baseURL = commMsg.base_url;
    HttpConfig().headers = () {
      var headerParams={
        'Authorization': "${commMsg!.token}",
        "App-id": commMsg.app_id,
        "channel": commMsg.channel,
        "version-no": commMsg.version_no,
      };
      if(commMsg.enable_gray==true){
        headerParams["containers"] ='canary' ;
      }
      return headerParams;
    };

    NativeChannelBridge.instance.appCommMsg = commMsg;
    if (['1', '2'].contains(commMsg.appEnvType.toString())) {
      HttpConfig().isNeedCrypt = true;
    } else {
      // 初始化 不管
      HttpConfig().isNeedCrypt = false;
    }
  } else {
    // 初始化 不管
    HttpConfig().isNeedCrypt = false;
  }
  if (isDev == true) {
    // 使用默认调试的参数

    // HttpConfig().baseURL = "https://api.kaichats.com/";
    // HttpConfig().baseURL = "http://test-api-ai.ai-chat.ltd/";
    // HttpConfig().baseURL = "http://dev-api.ai-chat.ltd/";

    // HttpConfig().baseURL = "http://192.168.11.44:8090/";

    HttpConfig().isNeedCrypt = true ;

    HttpConfig().baseURL = "http://stg-app-api.ai-chat.ltd/";

    HttpConfig().headers = () {
      return {
        'Authorization':
            "${NativeChannelBridge.instance.appCommMsg?.token ?? ""}",
        "App-id": "101",
        "channel": "ios",
        "version-no": "1.3.0"
      };
    };

    await mockLogin();
  }
}

//模拟登录后原生转过来的参数

Future<void> mockLogin() async {
  try {
    // var params = {"email": "z1798557005@gmail.com", "password": "Zqh888888."};

    var params = {"email": "timmy97tankaho@gmail.com", "password": "Aa123456."};
    // var params = {"email": "kaizheng71@gmail.com", "password": "a12345678!"};

    // var params = {"email": "dahaolin57@gmail.com", "password": "&lin12345"};

    // var params = {"email": "z1798557005@gmail.com", "password": "Zqh888888."};

    // var params = {"email": "xcy0402@gmail.com", "password": "aA&123456"};
    // var params = {"email": "xjy2017@gmail.com", "password": "aa@123456"};

    // var params = {"email": "dahaolin57@gmail.com", "password": "&lin12345"};   //61eb

    // var params = {"email": "caowenjun808@gmail.com", "password": "@web6620"};

    // var params = {"email": "z1798557005@gmail.com", "password": "Zqh888888."};

    // var params = {

    //   "email": "huangyusheng0660@gmail.com",

    //   "password": "Aa12345678!"

    // };

    print('Current Account : $params');

    var resp = await HttpManager().post(API.emailLogin, params);
    var json = {
      "token": resp!.data["access_token"].toString(),
      "iconUrl": resp.data["user_info"]["profile_picture"],
      "base_url": "",
      "channel": "ios",
      "version_no": "1.0.0",
      "device_type": 2, // 预发布 想直接谷歌 上传 ，请根据 安卓是 2，ios 1；
      "email": resp.data["user_info"]["account"],
      "userId": resp.data["user_info"]["id"].toString(),
      "app_id": 101,
      'google_email': resp.data["user_info"]['google_email']??resp.data["user_info"]["account"],
      'apple_user_id': resp.data["user_info"]['apple_id'],
      'appEnvType': 0, // 配置
      'isUseCrypto': false, // 配置
      'page' :'wallet',
      'parameter' :"{}",
      'enable_gray': false,
      'isAppleEnterprise': null,
    };

    var appCommMsg = AppCommMsg.fromJson(json);

    NativeChannelBridge.instance.appCommMsg = appCommMsg;

    // await SP().setAppLoginInfo(loginInfo)

    Log.logger.d(appCommMsg.toJson());
  } catch (e) {
    Log.logger.e(e);

    print(e);
  }
}
